package org.jadapter.tests.zcml;


import java.io.IOException;
import java.io.InputStream;

import java.util.LinkedList;
import java.util.List;

import org.jadapter.JAdapter;

import org.jadapter.registry.Components;
import org.jadapter.tests.examples.CommaSeparated;
import org.jadapter.tests.examples.CommaSeparatedList;


import org.jadapter.zcml.ZCML;

import com.thoughtworks.xstream.XStream;

import junit.framework.TestCase;

@SuppressWarnings("unchecked")
public class TestZCML extends TestCase {
    
    XStream x;
    String xml;
    ZCML zcml;
    InputStream input;
    List<String> list;
    
    
    @Override public void setUp(){

        list = new LinkedList<String>();
        list.add("Foo");
        list.add("Bar");
        
        x = ZCML.getXStream();
        
        input = this.getClass().getClassLoader().getResourceAsStream("org/jadapter/tests/zcml/test.xml");
    }
    
    @Override public void tearDown() throws IOException{
        System.out.print(xml);       
        System.out.println();
        input.close();
        Components.destroy();
    }
    
    public void testZCMLAPI() {
        // parse the input ZCML file and register everything found
        new ZCML(input).process();
        
        CommaSeparated cs = Components.get(CommaSeparated.class, list);
        assertEquals("comma separated list", "Foo,Bar", cs.getCommaSeparated());        
    }    
    
    public void testSimpleAPI () {
        ZCML.process(input);
        
        CommaSeparated cs = Components.get(CommaSeparated.class, list);
        assertEquals("comma separated list", "Foo,Bar", cs.getCommaSeparated());        
    }
    
    public void testJAdapterWriter()  {
        
        JAdapter<CommaSeparated,List> adapter = new JAdapter<CommaSeparated,List> (
                    CommaSeparatedList.class,
                    CommaSeparated.class,
                    List.class);
        
        
        zcml = new ZCML();
        zcml.addDirective(adapter);
        
        zcml.process();
        
        CommaSeparated cs = Components.get(CommaSeparated.class, list);
        assertNotNull(cs);
        assertEquals("comma separated list", "Foo,Bar", cs.getCommaSeparated());
        
        xml = x.toXML(zcml);
        
    }
    
    public void testJAdapterReader() throws IOException {
        assertNotNull(input);           
        
        zcml = (ZCML)x.fromXML(input);
        assertNotNull(zcml);
        
        xml = x.toXML(zcml);
        
        zcml.process();
        
        CommaSeparated cs = Components.get(CommaSeparated.class, list);
        assertNotNull(cs);
        assertEquals("comma separated list", "Foo,Bar", cs.getCommaSeparated());
    } 

}
